<?php
/*
 * Created on 2011-8-20
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 
class Setting extends CI_Controller {
	
	/**
	 * @return CI_Controller
	 */
	public static function get_instance() {
		
	}
	
	function index(){
		if($this->session->userdata('is_logged_in'))
		{
			$this->load->model('user_model');
			$this->load->model('user_setting_model');
				
		//用户的setting信息
			$result=$this->user_setting_model->get_info();
	   	//还没有该用户的user_setting信息
			if(!$result){
				$data=array(
						'setting_model'=>'basic',
						'photo_path'=>base_url() . 'person_photo/portrait_default.jpg',
						'n_name'=>'',
						'company'=>'',
						'university'=>'',
						'birthday'=>'',
						'phone'=>''
					);
				$this->load->view('setting/main',$data);
			}
			else
			{
				foreach ($result as $row)
				{
					$photo_path=$row->photo_path;
					if($row->photo_path==""){
						$photo_path=base_url() . 'avatars/default.jpg';
					}
					else{
						//如果所存路径的文件丢失，则指向默认头像
						$file_path= substr($photo_path,strlen(base_url()));
						
						if(!file_exists($file_path))
						{
							$this->user_setting_model->update_photo_path('avatars/default.jpg');							
							$photo_path=base_url() . 'avatars/default.jpg';
						}
					}
					
					$birthday="";
					if($row->birthday!="")
					{
						$birthday=date('Y-m-d',strtotime($row->birthday));
					}
   					$data=array(
   						'setting_model'=>'basic',
   						'photo_path'=>$photo_path,
							'n_name'=>$row->n_name,
							'company'=>$row->company,
							'university'=>$row->university,
							'birthday'=>$birthday,
							'phone'=>$row->phone
   					);
   					$this->load->view('setting/main',$data);
				}	
			}	
		}
		else 
			redirect(base_url());
	}
	
	function save_setting(){
		if($this->session->userdata('is_logged_in'))
		{
			$this->load->library('form_validation');
			$this->form_validation->set_rules('n_name', 'Name', 'trim|required');
			if($this->form_validation->run() == FALSE)
			{
				$data=array(
					'setting_model'=>'basic',
					'n_name'=>$_POST['n_name'],
					'birthday'=> $_POST['birthday'],
					'photo_path'=>$_POST['photo_path'],
					'company'=> $_POST['company'],
					'university'=>$_POST['university'],
					'phone'=>$_POST['mobile']
				);
				$this->load->view('setting/main',$data);
			}
			else
			{
				$this->load->model('user_setting_model');
				$result=$this->user_setting_model->get_info();
				
				$query=false;
				if(!$result)
				{
					$query=$this->user_setting_model->create_setting();
				}
				else
				{
					$query=$this->user_setting_model->save_setting();	
				}
				if($query){
					$data=array(
						'setting_model'=>'basic',
						'n_name'=>$_POST['n_name'],
						'birthday'=> $_POST['birthday'],
						'photo_path'=>$_POST['photo_path'],
						'company'=> $_POST['company'],
						'university'=>$_POST['university'],
						'phone'=>$_POST['mobile']
					);
					$this->load->view('setting/main',$data);
				}
			}		
		}
		else 
			redirect(base_url());
	}
	
	function photo(){
		$this->load->helper('image');

		//Image Locations
		
		$upload_dir = "person_photo"; 				// The directory for the images to be saved in
		$upload_path = $upload_dir."/";				// The path to where the image will be saved
		$upload_path_large=$upload_path."large_photo/";
		$large_image_prefix = "template"; 			// The prefix name to large image 临时大图
		$thumb_image_prefix = "portrait";			// The prefix name to the thumb image小图
		$large_image_name = $large_image_prefix;     // New name of the large image (append the timestamp to the filename)
		$thumb_image_name = $thumb_image_prefix;     // New name of the thumbnail image (append the timestamp to the filename)
		$max_file = "3"; 							// Maximum file size in MB
		$max_width = "300";							// Max width allowed for the large image
		$thumb_width = "75";						// Width of thumbnail image
		$thumb_height = "75";						// Height of thumbnail image
		// Only one of these image types should be allowed for upload
		$allowed_image_types = array('image/pjpeg'=>"jpg",'image/jpeg'=>"jpg",'image/jpg'=>"jpg",'image/png'=>"png",'image/x-png'=>"png",'image/gif'=>"gif");
		$allowed_image_ext = array_unique($allowed_image_types); // do not change this
		$image_ext="";
		foreach ($allowed_image_ext as $mime_type => $ext) {
			$image_ext.= strtoupper($ext)." ";
		}
		
		if(isset($_GET['user_file_ext']))
		{
			$large_image_location = $upload_path_large.$large_image_name . "_" . $this->session->userdata('user_id') . $_GET['user_file_ext'] ;
			$thumb_image_location = $upload_path.$thumb_image_name. "_" . $this->session->userdata('user_id'). $_GET['user_file_ext'];
		}
		else
		{
			$large_image_location = $upload_path_large.$large_image_name . "_" . $this->session->userdata('user_id') ;
			$thumb_image_location = $upload_path.$thumb_image_name. "_" . $this->session->userdata('user_id') ;
		}
		
		//Check to see if any images with the same name already exist
		if (file_exists($large_image_location)){
			if(file_exists($thumb_image_location)){
				$thumb_photo_exists = "<img src=\"".$upload_path.$thumb_image_name. "_" . $this->session->userdata('user_id')."\" alt=\"Thumbnail Image\"/>";
			}
			else{
				$thumb_photo_exists = "";
			}
			$large_photo_exists = "<img src=\"".$upload_path_large.$large_image_name  . "_" . $this->session->userdata('user_id')."\" alt=\"Large Image\"/>";
		}
		else {
			$large_photo_exists = "";
			$thumb_photo_exists = "";
		}
		
		if($this->session->userdata('is_logged_in'))
		{	
			if(isset($_POST["upload_thumbnail"]) && strlen($large_photo_exists)>0) {
				//Get the new coordinates to crop the image.
				$x1 = $_POST["x1"];
				$y1 = $_POST["y1"];
				$x2 = $_POST["x2"];
				$y2 = $_POST["y2"];
				$w = $_POST["w"];
				$h = $_POST["h"];
				//Scale the image to the thumb_width set above
				$scale = $thumb_width/$w;
				$cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
				
			//将生成的头像添加到user_setting表中
				$this->load->model('user_setting_model');
			//用户的setting信息
				$result=$this->user_setting_model->get_info();
			//如果没有user_setting就直接创建，如果存在了就更新头像的地址
				$query=false;
				if(!$result){
					$query=$this->user_setting_model->createBysavePhoto($thumb_image_location);
				}
				else
				{
					$query=$this->user_setting_model->update_photo_path($thumb_image_location);
				}
			//如果保存用户的头像成功，则跳转到basic页面
				if($query)
				{
					$result=$this->user_setting_model->get_info();
					foreach ($result as $row)
					{
						$birthday="";
						if($row->birthday!="")
						{
							$birthday=date('Y-m-d',strtotime($row->birthday));
						}
   						$data=array(
   							'setting_model'=>'basic',
   							'photo_path'=>base_url() . $thumb_image_location,
							'n_name'=>$row->n_name,
							'company'=>$row->company,
							'university'=>$row->university,
							'birthday'=>$birthday,
							'phone'=>$row->phone
   						);
   						$this->load->view('setting/main',$data);
					}	
				}
				return;
			}
				
				
				
		// 点击上传按钮之后相应的action	
			if (isset($_POST["upload"])) 
			{
					//Get the file information
				$userfile_name = $_FILES['image']['name'];
				$userfile_tmp = $_FILES['image']['tmp_name'];
				$userfile_size = $_FILES['image']['size'];
				$userfile_type = $_FILES['image']['type'];
				$filename = basename($_FILES['image']['name']);
				$file_ext = strtolower(substr($filename, strrpos($filename, '.') + 1));

				//Only process if the file is a JPG, PNG or GIF and below the allowed limit
				if((!empty($_FILES["image"])) && ($_FILES['image']['error'] == 0)) {

					foreach ($allowed_image_types as $mime_type => $ext) {
						//loop through the specified image types and if they match the extension then break out
						//everything is ok so go and check file size
						if($file_ext==$ext && $userfile_type==$mime_type){
							$error = "";
							break;
						}else{
							$error = "Only <strong>".$image_ext."</strong> images accepted for upload<br />";
						}
					}
					//check if the file size is above the allowed limit
					if ($userfile_size > ($max_file*1048576)) {
						$error.= "Images must be under ".$max_file."MB in size";
					}

				}
				else{
					$error= "Select an image for upload";
				}
				//Everything is ok, so we can upload the image.
				if (strlen($error)==0){
		
					if (isset($_FILES['image']['name'])){

						//this file could now has an unknown file extension (we hope it's one of the ones set above!)
						$large_image_location = $large_image_location.".".$file_ext;
						$thumb_image_location = $thumb_image_location.".".$file_ext;

						//put the file ext in the session so we know what file to look for once its uploaded

//						$data_ext=array('user_file_ext'=>".".$file_ext);
//						$this->session->set_userdata($data_ext);


						move_uploaded_file($userfile_tmp, $large_image_location);
						chmod($large_image_location, 0777);

						$width = getWidth($large_image_location);
						$height = getHeight($large_image_location);
						//Scale the image if it is greater than the width set above
						if ($width > $max_width){
							$scale = $max_width/$width;
							$uploaded = resizeImage($large_image_location,$width,$height,$scale);
						}else{
							$scale = 1;
							$uploaded = resizeImage($large_image_location,$width,$height,$scale);
						}
						//Delete the thumbnail file so the user can create a new one
						/*if (file_exists($thumb_image_location)) {
							unlink($thumb_image_location);
							}*/
					}

				}
				$data=array('op'=>'upload','user_file_ext'=>".".$file_ext,'setting_model'=>'photo');
				$this->load->view('setting/main',$data);
				return;
			}
			$data=array('op'=>'','setting_model'=>'photo');
			$this->load->view('setting/main',$data);
			 
		}
		else 
			redirect(base_url());
	}
	
	function basic(){
		if($this->session->userdata('is_logged_in'))
		{
			$this->load->model('user_model');
			$this->load->model('user_setting_model');
				
		//用户的setting信息
			$result=$this->user_setting_model->get_info();
	   	//还没有该用户的user_setting信息
			if(!$result){
				$data=array(
						'setting_model'=>'basic',
						'photo_path'=>base_url() . 'person_photo/portrait_default.jpg',
						'n_name'=>'',
						'company'=>'',
						'university'=>'',
						'birthday'=>'',
						'phone'=>''
						);
				$this->load->view('setting/main',$data);
			}
			else
			{
				foreach ($result as $row)
				{
					$photo_path=$row->photo_path;
					if($row->photo_path==""){
						$photo_path=base_url() . 'avatars/default.jpg';
					}
					else{
						//如果所存路径的文件丢失，则指向默认头像
						$file_path= substr($photo_path,strlen(base_url()));
						
						if(!file_exists($file_path))
						{
							$this->user_setting_model->update_photo_path('avatars/default.jpg');							
							$photo_path=base_url() . 'avatars/default.jpg';
						}
					}
					
					$birthday="";
					if($row->birthday!="")
					{
						$birthday=date('Y-m-d',strtotime($row->birthday));
					}
   					$data=array(
   						'setting_model'=>'basic',
   						'photo_path'=>$photo_path,
						'n_name'=>$row->n_name,
						'company'=>$row->company,
						'university'=>$row->university,
						'birthday'=>$birthday,
						'phone'=>$row->phone
   					);
   					$this->load->view('setting/main',$data);
				}	
			}	
		}
		else 
			redirect(base_url());
	}
	
	function avatar(){
		if($this->session->userdata('is_logged_in'))
		{
			$this->load->model('user_model');
			$this->load->model('user_setting_model');
				
		//用户的setting信息
			$result=$this->user_setting_model->get_info();
			if(!$result)
				$photo_path="";
			else{
				foreach ($result as $row)
				{
					$photo_path=$row->photo_path;
				}
			}
				
			$data=array('setting_model'=>'avatar','photo_path'=>$photo_path);
			$this->load->view('setting/main',$data);		
		}
		else 
			redirect(base_url());
	}
	
	function avatardelete(){
		$error = "";
		$msg = "";
		
		$this->load->helper('image');
		$this->load->model('user_setting_model');
		$path=$_POST["path"];
		$file_path= substr($path,strlen(base_url()));
		$default_path=base_url()."avatars/default.jpg";
		$query=$this->user_setting_model->update_avatar($default_path);
		if(!deldir($file_path))
			$error = "删除旧头像出错：".$file_path;
			
		echo '{"error": "' . $error . '","msg": "' . $msg . '"}';
	}
	
	function avatarupload(){
		$this->load->helper('image');
		$uid=$this->session->userdata('user_id');
		$getStr=uploadFile($_POST,$_FILES,'avatar',$uid);
		
		if($getStr[0]=="" && $getStr[1]!=""){
			$this->load->model('user_setting_model');
			$error="";
			$msg="";
			
			$path = $getStr[1];
			$query=false;
			$query=$this->user_setting_model->update_avatar($path);
			if($query)
				$getStr[1] .="";
			else
				$getStr[0] .="设置出错，请待会儿重试.";
			
			echo "{";
			echo				"error: '" . $getStr[0] . "',\n";
			echo				"msg: '" . $getStr[1] . "'\n";
			echo "}";
		}
		else{
			echo "{";
			echo				"error: '" . $getStr[0] . "',\n";
			echo				"msg: '" . $getStr[1] . "'\n";
			echo "}";
		}
	}
	
	function interest(){
		if($this->session->userdata('is_logged_in'))
		{
			$data=array('setting_model'=>'interest');
			$this->load->view('setting/main',$data);			
		}
		else 
			redirect(base_url());
	}
	
	function account(){
		if($this->session->userdata('is_logged_in'))
		{
			$data=array('setting_model'=>'account');
			$this->load->view('setting/main',$data);			
		}
		else 
			redirect(base_url());
	}
	
	function sync(){
		if($this->session->userdata('is_logged_in'))
		{
			$data=array('setting_model'=>'sync');
			$this->load->view('setting/main',$data);			
		}
		else 
			redirect(base_url());
	}
	function notify(){
		if($this->session->userdata('is_logged_in'))
		{
			$data=array('setting_model'=>'notify');
			$this->load->view('setting/main',$data);			
		}
		else 
			redirect(base_url());
	}
	function privacy(){
		if($this->session->userdata('is_logged_in'))
		{
			$data=array('setting_model'=>'privacy');
			$this->load->view('setting/main',$data);			
		}
		else 
			redirect(base_url());
	}
} 
?>
